/*******************************************************************************
 * Copyright (c) 2010-2011 Robert Fraser                                       *
 *                                                                             *
 * Permission is hereby granted, free of charge, to any person obtaining a     *
 * copy of this software and associated documentation files (the "Software"),  *
 * to deal in the Software without restriction, including without limitation   *
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,    *
 * and/or sell copies of the Software, and to permit persons to whom the       *
 * Software is furnished to do so, subject to the following conditions:        *
 *                                                                             *
 *   - The above copyright notice and this permission notice shall be included *
 *     in all copies or substantial portions of the Software.                  *
 *                                                                             *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR  *
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,    *
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER      *
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING     *
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER         *
 * DEALINGS IN THE SOFTWARE.                                                   *
 *******************************************************************************/

using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace zeal.ui.util
{
    internal sealed class UndoStack
    {
        public const int MAX_UNDO_DEPTH = 200;

        private readonly LinkedList<IMemento> _undo = new LinkedList<IMemento>();
        private readonly LinkedList<IMemento> _redo = new LinkedList<IMemento>();
        private int _currentlyExecuting;

        public void push(IMemento memento)
        {
            if(_currentlyExecuting != 0)
                throw new InvalidOperationException("Items cannot be pushed onto the undo/redo stack while undoing/redoing");
            Debug.Assert(null != memento);
            _redo.Clear();
            push(_undo, memento);
        }

        public bool undo() 
        {
            if (_undo.Count == 0)
                return false;
            _currentlyExecuting++;
            IMemento memento = pop(_undo);
            memento.undo();
            push(_redo, memento);
            _currentlyExecuting--;
            return true;
        }

        public bool redo() 
        {
            if (_redo.Count == 0)
                return false;
            _currentlyExecuting++;
            IMemento memento = pop(_redo);
            memento.redo();
            push(_undo, memento);
            _currentlyExecuting--;
            return true;
        }
        
        public bool canUndo() { return _undo.Count > 0; }
        public bool canRedo() { return _redo.Count > 0; }

        private static void push(LinkedList<IMemento> stack, IMemento item)
        {
            Debug.Assert(null != item);
            if(stack.Count > MAX_UNDO_DEPTH)
                stack.RemoveLast();
            stack.AddFirst(item);
        }

        private static IMemento pop(LinkedList<IMemento> stack)
        {
            Debug.Assert(stack.Count > 0);
            IMemento item = stack.First.Value;
            stack.RemoveFirst();
            return item;
        }
    }

    internal interface IMemento
    {
        string name { get; set; }
        void undo();
        void redo();
    }

    internal sealed class Memento : IMemento
    {
        public string name { get; set; }
        public override string ToString() { return name; }

        public readonly Action revert;
        public readonly Action exec;

        public Memento(Action exec, Action revert) : this(exec, revert, null) { }
        public Memento(Action exec, Action revert, string name)
        {
            if(revert == null) throw new ArgumentNullException("revert");
            if(exec == null) throw new ArgumentNullException("exec");
            this.revert = revert;
            this.exec = exec;
            this.name = name;
        }

        public void undo() { revert(); }
        public void redo() { exec(); }
    }

    internal sealed class MultiMemento : IMemento
    {
        public string name { get; set; }
        public override string ToString() { return name; }

        private readonly LinkedList<Action> _undo = new LinkedList<Action>();
        private readonly LinkedList<Action> _redo = new LinkedList<Action>();

        public MultiMemento(string name)
        {
            this.name = name;
        }

        public void undo()
        {
            foreach(Action action in _undo)
                action();
        }

        public void redo()
        {
            foreach (var action in _redo)
                action();
        }

        public void add(IMemento a) 
        { 
            if(null != a)
            {
                Memento u = a as Memento;
                if(null != u)
                {
                    addUndo(u.revert);
                    addRedo(u.exec);
                }
                else
                {
                    addUndo(a.undo);
                    addRedo(a.redo);
                }
            } 
        }

        public void addUndo(Action a) { if(null != a) _undo.AddFirst(a); }
        public void addRedo(Action a) { if(null != a) _redo.AddLast(a); }
    }
}